package com.sgzn.sgpay.web.controller;


import com.sgzn.sgpay.constants.WXInfoConstants;
import com.sgzn.sgpay.model.request.SgsCallBackRequest;
import com.sgzn.sgpay.model.response.SgsResultResponse;
import com.sgzn.sgpay.service.SgsCallBackService;
import com.sgzn.sgpay.util.GenerateSignUtils;
import com.sgzn.sgpay.util.MessageUtil;
import com.sgzn.sgpay.web.handle.AssembleCommonHandle;
import com.sgzn.sgpay.web.request.Impl.PayCallbackRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 回调控制器
 * @author huangsenguang
 */
@Slf4j
@Controller
public class PayCallBackController {

    @Resource
    private SgsCallBackService sgsCallBackService;
    @Resource
    private AssembleCommonHandle assembleCommonHandle;

    private static final String SIGN = "sign";

    @RequestMapping("/payCallBack")
    @ResponseBody
    public String payCallBack(PayCallbackRequest request, HttpServletRequest httpServletRequest){

        try {
            Map<String,String> map = MessageUtil.parseXML(httpServletRequest);
            if (map == null) {
                return "";
            }
            log.info("[{}] WX response map：{}",map);

            //生成签文
            String checkSign = GenerateSignUtils.generateReturnSign(map, WXInfoConstants.MCH_API_KEY);
            if (checkSign.equals(map.get(SIGN))) {
                SgsCallBackRequest sgsCallBackRequest = this.assembleRequest(map, request);
                log.info("微信回调接口 接受到的信息：{}",map.toString());
                SgsResultResponse<String> response = this.sgsCallBackService.deposit(sgsCallBackRequest);
                return response.getResult();
            }

            //验签失败
            //封装 返回值
            StringBuffer buffer = new StringBuffer();
            buffer.append("<xml>");
            buffer.append("<return_code>FAIL</return_code>");
            buffer.append("<return_msg>验签失败</return_msg>");
            buffer.append("<xml>");
            log.error("微信回调失败return_code={}, return_msg={} response:{}", map.get("return_code"),map.get("return_msg"),buffer.toString());
            return buffer.toString();
        } catch (Exception e) {
            log.error("回调Ctrl出现异常：",e);
        } finally {
        }
        return "";

    }

    private SgsCallBackRequest assembleRequest(Map<String, String> map, PayCallbackRequest request) {
        SgsCallBackRequest sgsCallBackRequest = new SgsCallBackRequest();
        assembleCommonHandle.assemble(request, sgsCallBackRequest);
        sgsCallBackRequest.setReturn_code(map.get("return_code"));
        sgsCallBackRequest.setReturn_msg(map.get("return_msg"));
        //以下字段在return_code为SUCCESS的时候有返回
        sgsCallBackRequest.setAppid(map.get("appid"));
        sgsCallBackRequest.setMch_id(map.get("mch_id"));
        sgsCallBackRequest.setDevice_info(map.get("device_info"));
        sgsCallBackRequest.setNonce_str(map.get("nonce_str"));
        sgsCallBackRequest.setSign(map.get("sign"));
        sgsCallBackRequest.setSign_type(map.get("sign_type"));
        sgsCallBackRequest.setResult_code(map.get("result_code"));
        sgsCallBackRequest.setErr_code(map.get("err_code"));
        sgsCallBackRequest.setErr_code_des(map.get("err_code_des"));
        sgsCallBackRequest.setOpenid(map.get("openid"));
        sgsCallBackRequest.setIs_subscribe(map.get("is_subscribe"));
        sgsCallBackRequest.setTrade_type(map.get("trade_type"));
        sgsCallBackRequest.setBank_type(map.get("bank_type"));
        sgsCallBackRequest.setTotal_fee(map.get("total_fee"));
        sgsCallBackRequest.setSettlement_total_fee(map.get("settlement_total_fee"));
        sgsCallBackRequest.setFee_type(map.get("fee_type"));
        sgsCallBackRequest.setCash_fee(map.get("cash_fee"));
        sgsCallBackRequest.setCash_fee_type(map.get("cash_fee_type"));
        sgsCallBackRequest.setCoupon_fee(map.get("coupon_fee"));
        sgsCallBackRequest.setCoupon_count(map.get("coupon_count"));
        sgsCallBackRequest.setCoupon_type_$n(map.get("coupon_type_$n"));
        sgsCallBackRequest.setCoupon_id_$n(map.get("coupon_id_$n"));
        sgsCallBackRequest.setCoupon_fee_$n(map.get("coupon_fee_$n"));
        sgsCallBackRequest.setTransaction_id(map.get("transaction_id"));
        sgsCallBackRequest.setOut_trade_no(map.get("out_trade_no"));
        sgsCallBackRequest.setAttach(map.get("attach"));
        sgsCallBackRequest.setTime_end(map.get("time_end"));
        return sgsCallBackRequest;
    }

}

